# -*- coding: utf-8 -*-
from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                           QPushButton, QLabel, QSpinBox, QGroupBox, QSplitter,
                           QMessageBox)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont

from .widgets import DraggableListWidget, ScheduleTable, ScheduleCell, ClassCell
from ..core.scheduler import Scheduler
from ..utils.excel_handler import import_excel, download_template

class PhysicalEducationScheduler(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("体育课程安排系统")
        self.setGeometry(100, 100, 1400, 800)
        
        # 初始化数据
        self.student_data = None
        self.scheduler = Scheduler()
        self.all_classes = []
        self.unscheduled_classes = []
        
        # 初始化UI
        self.init_ui()
    
    def init_ui(self):
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Horizontal)
        splitter.setHandleWidth(5)
        splitter.setStyleSheet("""
            QSplitter::handle {
                background-color: #cccccc;
                border: 1px solid #999999;
            }
            QSplitter::handle:hover {
                background-color: #bbbbbb;
            }
        """)
        
        # 左侧面板
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        # 控制区域
        control_group = QGroupBox("控制面板")
        control_layout = QVBoxLayout()
        
        # 导入按钮
        import_btn = QPushButton("导入Excel数据", self)
        import_btn.clicked.connect(self.import_excel)
        control_layout.addWidget(import_btn)
        
        # 添加模板下载按钮
        template_btn = QPushButton("下载Excel模板", self)
        template_btn.clicked.connect(self.download_template)
        control_layout.addWidget(template_btn)
        
        # 添加自动排课按钮
        auto_schedule_btn = QPushButton("自动排课", self)
        auto_schedule_btn.clicked.connect(self.auto_schedule)
        control_layout.addWidget(auto_schedule_btn)
        
        # 添加清空课表按钮
        clear_btn = QPushButton("清空课表", self)
        clear_btn.clicked.connect(self.clear_schedule_with_confirm)
        control_layout.addWidget(clear_btn)
        
        # 每日学生上限设置
        limit_layout = QHBoxLayout()
        limit_label = QLabel("每日学生上限:", self)
        limit_layout.addWidget(limit_label)
        
        self.limit_spinbox = QSpinBox(self)
        self.limit_spinbox.setRange(1, 1000)
        self.limit_spinbox.setValue(self.scheduler.max_students_per_day)
        self.limit_spinbox.valueChanged.connect(self.update_max_students)
        limit_layout.addWidget(self.limit_spinbox)
        control_layout.addLayout(limit_layout)
        
        control_group.setLayout(control_layout)
        left_layout.addWidget(control_group)
        
        # 未安排课程列表
        unscheduled_group = QGroupBox("未安排课程")
        unscheduled_layout = QVBoxLayout()
        self.unscheduled_list = DraggableListWidget()
        unscheduled_layout.addWidget(self.unscheduled_list)
        unscheduled_group.setLayout(unscheduled_layout)
        left_layout.addWidget(unscheduled_group)
        
        # 右侧面板
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        # 数据统计
        stats_group = QGroupBox("数据统计")
        stats_layout = QVBoxLayout()
        
        # 总体统计
        total_stats_layout = QHBoxLayout()
        self.college_count_label = QLabel("学院数量: 0")
        self.major_count_label = QLabel("专业数量: 0")
        self.total_students_label = QLabel("学生总数: 0")
        self.male_students_label = QLabel("男生总数: 0")
        self.female_students_label = QLabel("女生总数: 0")
        
        total_stats_layout.addWidget(self.college_count_label)
        total_stats_layout.addWidget(self.major_count_label)
        total_stats_layout.addWidget(self.total_students_label)
        total_stats_layout.addWidget(self.male_students_label)
        total_stats_layout.addWidget(self.female_students_label)
        
        stats_layout.addLayout(total_stats_layout)
        
        # 每日统计
        self.daily_stats_labels = {}
        for day in self.scheduler.days:
            day_label = QLabel(f"{day}安排学生数: 0")
            self.daily_stats_labels[day] = day_label
            stats_layout.addWidget(day_label)
        
        stats_group.setLayout(stats_layout)
        right_layout.addWidget(stats_group)
        
        # 课表
        schedule_group = QGroupBox("课程安排")
        schedule_layout = QVBoxLayout()
        self.schedule_table = ScheduleTable(self)
        self.schedule_table.setHorizontalHeaderLabels(self.scheduler.days)
        self.schedule_table.setVerticalHeaderLabels(self.scheduler.time_slots)
        
        # 设置表头样式
        self.schedule_table.horizontalHeader().setStyleSheet("""
            QHeaderView::section {
                background-color: #4a4a4a;
                color: white;
                padding: 5px;
                border: 1px solid #666666;
                font-weight: bold;
            }
        """)
        self.schedule_table.verticalHeader().setStyleSheet("""
            QHeaderView::section {
                background-color: #4a4a4a;
                color: white;
                padding: 5px;
                border: 1px solid #666666;
                font-weight: bold;
            }
        """)
        
        # 初始化课表单元格
        for row in range(3):
            for col in range(5):
                cell = ScheduleCell()
                cell.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.schedule_table.setItem(row, col, cell)
        
        schedule_layout.addWidget(self.schedule_table)
        schedule_group.setLayout(schedule_layout)
        right_layout.addWidget(schedule_group)
        
        # 添加左右面板到分割器
        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)
        
        # 设置初始分割比例（左:右 = 1:2）
        splitter.setSizes([400, 800])
        
        # 将分割器添加到主布局
        main_layout.addWidget(splitter)
    
    def handle_class_move(self, class_info, source_pos, target_row, target_col):
        """处理课表内的班级移动"""
        if source_pos['row'] == target_row and source_pos['col'] == target_col:
            return  # 如果是同一个位置，不做处理
        
        day = self.scheduler.days[target_col]
        
        # 检查目标时间段是否可以安排该班级
        # 注意：需要先从源位置移除才能正确计算目标日期的学生数
        source_cell = self.schedule_table.item(source_pos['row'], source_pos['col'])
        if source_cell and source_cell.classes:
            # 从源位置移除班级
            for i, cls in enumerate(source_cell.classes):
                if self.format_class_info(cls) == self.format_class_info(class_info):
                    source_cell.classes.pop(i)
                    self.update_cell_display(source_cell)
                    break
        
        # 检查是否可以安排到目标位置
        if self.scheduler.can_schedule_class(class_info, day, self.schedule_table):
            # 更新目标位置
            target_cell = self.schedule_table.item(target_row, target_col)
            if not target_cell.classes:
                target_cell.classes = []
            target_cell.classes.append(class_info)
            self.update_cell_display(target_cell)
        else:
            # 如果不能安排到目标位置，将班级添加回源位置
            source_cell.classes.append(class_info)
            self.update_cell_display(source_cell)
            QMessageBox.warning(self, "警告", "该时间段学生数量超过限制")
        
        # 更新统计信息
        self.update_daily_stats()

    def handle_class_return(self, class_info_text):
        """处理班级被拖回未安排列表"""
        # 在所有时间槽中查找并移除该班级
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                if cell and cell.classes:
                    for class_info in cell.classes[:]:
                        if self.format_class_info(class_info) == class_info_text:
                            cell.classes.remove(class_info)
                            self.update_cell_display(cell)
                            # 将班级添加回未安排列表
                            if class_info not in self.unscheduled_classes:
                                self.unscheduled_classes.append(class_info)
                            break
        
        # 更新未安排列表显示
        self.update_unscheduled_list()
        # 更新统计信息
        self.update_daily_stats()

    def update_cell_display(self, cell):
        """更新单元格显示"""
        # 清除现有的部件
        for widget in cell.widgets:
            self.schedule_table.removeCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell)
            )
        cell.widgets.clear()
        
        if cell.classes:
            # 创建容器部件
            container = QWidget()
            layout = QVBoxLayout(container)
            layout.setSpacing(1)  # 减小间距
            layout.setContentsMargins(1, 1, 1, 1)  # 减小边距
            
            # 为每个班级创建可拖动的部件
            for class_info in cell.classes:
                class_widget = ClassCell(class_info)
                layout.addWidget(class_widget)
            
            # 设置单元格的部件
            self.schedule_table.setCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell),
                container
            )
            cell.widgets.append(container)
            
            # 调整行高以适应内容
            self.schedule_table.resizeRowToContents(self.schedule_table.row(cell))
        else:
            self.schedule_table.removeCellWidget(
                self.schedule_table.row(cell),
                self.schedule_table.column(cell)
            )

    def update_unscheduled_list(self):
        """更新未安排课程列表"""
        self.unscheduled_list.clear()
        # 按学院、专业、年级排序
        sorted_classes = sorted(self.unscheduled_classes, 
                              key=lambda x: (x['college'], x['major'], x['grade']))
        for class_info in sorted_classes:
            item = QListWidgetItem(self.format_class_info(class_info))
            # 存储完整的班级信息
            item.setData(Qt.ItemDataRole.UserRole, str(class_info))
            self.unscheduled_list.addItem(item)

    def process_imported_data(self):
        """处理导入的数据"""
        if self.student_data is None:
            return
        
        # 清空现有数据
        self.unscheduled_list.clear()
        self.clear_schedule()
        self.all_classes = []
        self.unscheduled_classes = []
        
        # 处理数据
        for _, row in self.student_data.iterrows():
            class_info = {
                'college': row['学院'],
                'major': row['专业'],
                'grade': row['年级'],
                'male': row['男生人数'],
                'female': row['女生人数']
            }
            self.all_classes.append(class_info)
            self.unscheduled_classes.append(class_info)
        
        # 更新未安排列表
        self.update_unscheduled_list()
        
        # 更新统计信息
        self.update_statistics()
    
    def clear_schedule(self):
        """清空课表"""
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                cell.classes = []
                cell.setText("")
    
    def update_statistics(self):
        """更新统计信息"""
        if self.student_data is not None:
            # 计算统计数据
            college_count = len(self.student_data['学院'].unique())
            major_count = len(self.student_data[['学院', '专业']].drop_duplicates())
            total_male = self.student_data['男生人数'].sum()
            total_female = self.student_data['女生人数'].sum()
            total_students = total_male + total_female
            
            # 更新显示
            self.college_count_label.setText("学院数量: %d" % college_count)
            self.major_count_label.setText("专业数量: %d" % major_count)
            self.total_students_label.setText("学生总数: %d" % total_students)
            self.male_students_label.setText("男生总数: %d" % total_male)
            self.female_students_label.setText("女生总数: %d" % total_female)
    
    def update_max_students(self, value):
        """更新每日学生上限"""
        self.scheduler.max_students_per_day = value
    
    def download_template(self):
        """下载Excel模板"""
        download_template(self)
    
    def import_excel(self):
        """导入Excel数据"""
        self.student_data = import_excel(self)
        if self.student_data is not None:
            self.process_imported_data()
    
    def auto_schedule(self):
        """自动排课"""
        scheduled_classes = self.scheduler.auto_schedule(
            self.unscheduled_classes,
            self.schedule_table,
            self
        )
        
        # 更新课表显示
        for class_info in scheduled_classes:
            self.unscheduled_classes.remove(class_info)
            self.update_cell_display(self.schedule_table.item(
                self.scheduler.time_slots.index(class_info['slot']),
                self.scheduler.days.index(class_info['day'])
            ))
        
        # 更新未安排列表
        self.update_unscheduled_list()
        
        # 更新统计信息
        self.update_daily_stats()
        
        # 显示结果信息
        if scheduled_classes:
            QMessageBox.information(self, "成功", 
                                  "成功安排了%d个班级的课程" % len(scheduled_classes))
        else:
            QMessageBox.warning(self, "警告", 
                              "无法安排任何班级，请检查每日学生上限是否合理")

    def update_daily_stats(self):
        """更新每日统计信息"""
        for day in self.scheduler.days:
            total_male = 0
            total_female = 0
            for cell in self.scheduler.get_day_cells(day, self.schedule_table):
                if cell and cell.classes:
                    for class_info in cell.classes:
                        total_male += class_info['male']
                        total_female += class_info['female']
            total = total_male + total_female
            self.daily_stats_labels[day].setText(
                "%s安排学生数: %d (男:%d 女:%d)" % (day, total, total_male, total_female)
            )

    def format_class_info(self, class_data):
        """格式化班级信息"""
        return "%s-%s-%s年级(男:%d 女:%d)" % (
            class_data['college'],
            class_data['major'],
            class_data['grade'],
            class_data['male'],
            class_data['female']
        )

    def clear_schedule_with_confirm(self):
        """清空课表，带确认对话框"""
        reply = QMessageBox.question(
            self,
            "确认清空",
            "确定要清空当前课表吗？所有已安排的课程将返回到未安排列表。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.clear_schedule_and_reset()

    def clear_schedule_and_reset(self):
        """清空课表并重置所有相关数据"""
        # 将所有已安排的班级返回到未安排列表
        for row in range(3):
            for col in range(5):
                cell = self.schedule_table.item(row, col)
                if cell and cell.classes:
                    # 将班级添加回未安排列表
                    for class_info in cell.classes:
                        if class_info not in self.unscheduled_classes:
                            self.unscheduled_classes.append(class_info)
                    # 清空单元格
                    cell.classes = []
                    self.update_cell_display(cell)
        
        # 更新未安排列表显示
        self.update_unscheduled_list()
        
        # 更新统计信息
        self.update_daily_stats()
        
        # 显示成功消息
        QMessageBox.information(self, "成功", "课表已清空，所有课程已返回未安排列表")

    def handle_class_drop(self, class_info_text, row, col):
        """处理从未安排列表拖放到课表"""
        day = self.scheduler.days[col]
        
        # 解析班级信息
        for class_data in self.unscheduled_classes[:]:  # 使用切片创建副本
            if self.format_class_info(class_data) == class_info_text:
                # 检查该时间段是否可以安排该班级
                if self.scheduler.can_schedule_class(class_data, day, self.schedule_table):
                    # 更新课表显示
                    cell = self.schedule_table.item(row, col)
                    if not cell.classes:
                        cell.classes = []
                    cell.classes.append(class_data)
                    self.update_cell_display(cell)
                    
                    # 从未安排列表中移除
                    self.unscheduled_classes.remove(class_data)
                    self.update_unscheduled_list()
                    
                    # 更新统计信息
                    self.update_daily_stats()
                else:
                    QMessageBox.warning(self, "警告", "该时间段学生数量超过限制")
                break 